var core = require('../../core/enocean.js');
var fs = require('fs');
var PATH_TEACHING = '/../../modules/stats/teachin.json';
var co = require('../../sources/enocean.js');
var database = require('../../core/database.js');

var teachin = function(req, res) {
	
	req.connection.setTimeout(65*1000);

	core.isTeachIn(function (teaching) {
		if (teaching) {
			
			res.end('{"code":"already_teaching"}\n');

		} else {

			var type = req.params.type;
			var validTypes = core.availableSensors;
	
			// Check if the type of sensor to teach is known
			if (validTypes.indexOf(type) != -1) {
		
				var teachableSensor = new Object();
				teachableSensor.date = new Date();
				teachableSensor.type = type;

				fs.writeFile(__dirname + PATH_TEACHING, JSON.stringify(teachableSensor), 'utf8', function (err) {

					if (err) throw err;
				
					// Now we wait for the backend to insert the sensor
					var watcher = fs.watch(__dirname+PATH_TEACHING, function (event, filename) {
						if (event == 'change') {
							fs.readFile(__dirname + PATH_TEACHING, 'utf-8', function(error, data) {
							
								if (error) throw error;
								core.isTeachIn(function (teaching2) {
									if (!teaching2) {
										res.end('{"code":"OK"}\n');
										watcher.close();
									}
								});
							});
						}
					});
				});
			} else {
				res.end('{"code":"KO"}');
			}
		}
	});
}

var teachinOutlet = function (req, res) {
	co.getSocket(function (socket){	
		if (socket.write('A55A6B0510000000FF9F1E04306E')) {
			
			
			res.end('{"code":"OK"}\n');
			
			database.storeSensor({
				id: 1337,
				org: 0,
				func: 0,
				type: 0,
				desc: 'outlet'
			});
		}
		else {
			res.end('{"code":"KO"}\n');
		}	
	});

}

module.exports.teachin = teachin;
module.exports.teachinOutlet = teachinOutlet;
